import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt


def getfun(function_path,function_png_path):
    df = pd.read_pickle(function_path)
    df['fail_case_cnt'] = df['fail_case_cnt'].astype(int)
    df['pass_case_cnt'] = df['pass_case_cnt'].astype(int)
    print(df)
    print("fail_case_cnt:"+str(df['fail_case_cnt']))
    print("pass_case_cnt:" + str(df['pass_case_cnt']))


    plt.figure(figsize=(8, 4))
    plt.rcParams['font.sans-serif'] = ["SimHei"]
    plt.bar(df['functionname'], df['fail_case_cnt'], label='失败次数', color='red')
    plt.bar(df['functionname'], df['pass_case_cnt'], label='通过次数', color='green')
    plt.xlabel('功能名称')
    plt.ylabel('次数')
    plt.title('不同功能对应的成功次数和失败次数')
    plt.legend()
    # 保存图表为图像文件
    plt.savefig(function_png_path, format='png')
    plt.close()

def getpass(pass_path,pass_png_path):
    df = pd.read_pickle(pass_path)
    df['fail_case_cnt'] = df['fail_case_cnt'].astype(int)
    df['pass_case_cnt'] = df['pass_case_cnt'].astype(int)
    print(df)
    # 计算总和
    total_fail = df['fail_case_cnt'].sum()
    total_pass = df['pass_case_cnt'].sum()

    # 计算占比
    fail_percent = (total_fail / (total_fail + total_pass)) * 100
    pass_percent = (total_pass / (total_fail + total_pass)) * 100

    print("fail_percent:"+str(fail_percent))
    print("pass_percent:" + str(pass_percent))

    # 创建标签
    labels = ['失败', '成功']
    # 创建占比列表
    sizes = [fail_percent, pass_percent]

    # 颜色
    colors = ['red', 'green']

    # 突出 Fail Cases 部分
    explode = (0.1, 0)  # 突出 Fail Cases 部分

    # 绘制饼状图
    plt.rcParams['font.sans-serif'] = ["SimHei"]
    plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)

    # 添加标题
    plt.title('成功次数和失败次数分布')

    # 保存图像为PNG文件
    plt.savefig(pass_png_path, format='png')

    # 显示图表
    plt.show()


def virsul_step1(jobid,savepath):
    function_Path=savepath + 'data_function_distribute_'+ jobid + '.pkl'
    function_png_path=savepath + 'function_' + jobid + '.png'
    getfun(function_Path,function_png_path)
    pass_path=savepath + 'data_pass_'+ jobid + '.pkl'
    pass_png_path = savepath + 'pass_' + jobid + '.png'
    getpass(pass_path,pass_png_path)

if __name__ == '__main__':
    # 示例数据
    savepath = './csv/'
    jobid = '2023110812'
    virsul_step1(jobid,savepath)



